from rest_framework import status
from rest_framework.response import Response
from rest_framework.views import APIView
from QQLoginTool.QQtool import OAuthQQ


#第三方QQ登录接口   GET/oauth/qq/statues/?state=xxx
from mail import settings
from oauth.models import OAuthQQUser
from oauth.serializer import QQAuthUserSerializer
from oauth.utils import generate_save_token


class  QQAuthURLView(APIView):
    def get(self,request):   #获取code

        # auth_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101474184&redirect_uri=http://www.meiduo.site:8080/oauth_callback.html&state=/"
        state ='/'

        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI,
                        state=state)

        auth_url = oauth.get_qq_url()
        return Response({"auth_url":auth_url})

class OauthQQUserAPIView(APIView):    #获取token
    #https://graph.qq.com/oauth2.0/token
    def get(self,request):
        code = request.query_params.get('code')
        if not code:
            return Response(status= status.HTTP_400_BAD_REQUEST)
        oauth = OAuthQQ(client_id=settings.QQ_CLIENT_ID,
                        client_secret=settings.QQ_CLIENT_SECRET,
                        redirect_uri=settings.QQ_REDIRECT_URI)
        access_token = oauth.get_access_token(code)
        openid = oauth.get_open_id(access_token)
        try:
            qquser = OAuthQQUser.objects.get(openid = openid)
        except Exception as e:
            #不相信前端，加密openid
            access_token = generate_save_token(openid)
            return Response({'access_token':access_token})
        else:
            from rest_framework_jwt.settings import api_settings
            jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
            jwt_playload_handler = api_settings.JWT_PAYLOAD_HANDLER
            pay_load = jwt_playload_handler(qquser.user)
            token = jwt_encode_handler(pay_load)
            return Response({"token":token,
                             "username":qquser.user.username,
                             'user_id':qquser.user.id})

    def post(self,request):
        data = request.data
        serializer = QQAuthUserSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        qquser = serializer.save()

        from rest_framework_jwt.settings import api_settings
        jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
        jwt_playload_handler = api_settings.JWT_PAYLOAD_HANDLER
        pay_load = jwt_playload_handler(qquser.user)
        token = jwt_encode_handler(pay_load)

        return Response({"token": token,
                         "username": qquser.user.username,
                         'user_id': qquser.user.id})





